package com.shycloud.mido.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.shycloud.mido.common.core.constant.SecurityConstants;
import com.shycloud.mido.gateway.config.SwaggerProvider;
import com.shycloud.mido.gateway.util.RSAUtil;
import lombok.AllArgsConstructor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.addOriginalRequestUrl;

/**
 * @author npc
 * @date 2018/10/8
 * <p>
 * 全局拦截器，作用所有的微服务
 * <p>
 * 1. 对请求头中参数进行处理 from 参数进行清洗
 * 2. 重写StripPrefix = 1,支持全局
 * <p>
 * 支持swagger添加X-Forwarded-Prefix header  （F SR2 已经支持，不需要自己维护）
 */
@Component
@AllArgsConstructor
public class ShyRequestGlobalFilter implements GlobalFilter, Ordered {

	private static final String HEADER_NAME = "X-Forwarded-Prefix";

	private static Log logger = LogFactory.getLog(ShyRequestGlobalFilter.class);

	private final RedisTemplate redisTemplate;

	/**
	 * Process the Web request and (optionally) delegate to the next
	 * {@code WebFilter} through the given {@link GatewayFilterChain}.
	 *
	 * @param exchange the current server exchange
	 * @param chain    provides a way to delegate to the next filter
	 * @return {@code Mono<Void>} to indicate when request processing is complete
	 */
	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		//TODO 加入验签逻辑
		Map tempMap = (Map)(exchange.getRequest().getHeaders());
		logger.debug(JSONObject.toJSONString(tempMap));
		Map map = new HashMap(tempMap);

		//给redis增加一个可用token
		List<String> tokenList = (List<String>)map.get("authorization");
		if (tokenList != null) {
			String validToken = tokenList.get(0);
			if (!StringUtils.isEmpty(validToken) &&
					(validToken.startsWith("bearer") || validToken.startsWith("Bearer"))) {
				validToken = validToken.split("earer ")[1];
				redisTemplate.opsForValue().set("valid_token", validToken);
			}
		}

		if (!map.containsKey("platform")) {
		} else if (map.containsKey("sign")) {
			String sign = ((List<String>)map.get("sign")).get(0);
			map.remove("sign");
			map.remove("host");
			map.remove("user-agent");
			map.remove("accept-encoding");
			map.remove("content-length");
			map.remove("content-type");
			map.put("Authorization", (List<String>)map.get("authorization"));
			map.remove("authorization");

			Map<String, String> concatMap = new HashMap();
			concatMap.put("Authorization", ((List<String>)map.get("Authorization")).get(0));
			concatMap.put("platform", ((List<String>)map.get("platform")).get(0));
			concatMap.put("rand", ((List<String>)map.get("rand")).get(0));
			concatMap.put("timestamp", ((List<String>)map.get("timestamp")).get(0));
			TreeMap<String, String> orderMap = new TreeMap(concatMap);

			StringBuffer conStr = new StringBuffer("appId=jykj_happyzebra&");
			for (Map.Entry entry: orderMap.entrySet()) {
				conStr.append((String)entry.getKey() + "=" + (String)entry.getValue() + "&");
			}

			String concatString = conStr.toString();
			logger.debug("concatString: + " + concatString);

			try {
				String decrypted = RSAUtil.decrypt(sign, RSAUtil.getPrivateKey(RSAUtil.privateKey));
				if (!decrypted.equals(concatString)) {
					logger.debug("验签失败!");
					return returnFail(exchange);
				}
				logger.debug("验签通过!");
			} catch (Exception e) {
				logger.error("Error when verify sign!", e);
				return returnFail(exchange);
			}
		} else {
			return returnFail(exchange);
		}

//				}).build();

		// 1. 清洗请求头中from 参数
		ServerHttpRequest request = exchange.getRequest().mutate()
				.headers(httpHeaders -> {httpHeaders.remove(SecurityConstants.FROM);})
				.build();

		// 2. 重写StripPrefix
		addOriginalRequestUrl(exchange, request.getURI());
		String rawPath = request.getURI().getRawPath();
		String newPath = "/" + Arrays.stream(StringUtils.tokenizeToStringArray(rawPath, "/"))
				.skip(1L).collect(Collectors.joining("/"));
		ServerHttpRequest newRequest = request.mutate()
				.path(newPath)
				.build();
		exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, newRequest.getURI());

		// 3. 支持swagger添加X-Forwarded-Prefix header
		String path = request.getURI().getPath();
		if (!StringUtils.endsWithIgnoreCase(path, SwaggerProvider.API_URI)) {
			return chain.filter(exchange.mutate().request(newRequest).build());
		}
		String basePath = path.substring(0, path.lastIndexOf(SwaggerProvider.API_URI));
		return chain.filter(exchange.mutate()
				.request(newRequest.mutate()
						.header(HEADER_NAME, basePath)
						.build()).build());
	}

	@Override
	public int getOrder() {
		return -1000;
	}

	private Mono<Void> returnFail(ServerWebExchange exchange) {
		ServerHttpResponse response = exchange.getResponse();
		JSONObject message = new JSONObject();
		message.put("status", -1);
		message.put("data", "鉴权失败");
		byte[] bits = message.toJSONString().getBytes(StandardCharsets.UTF_8);
		DataBuffer buffer = response.bufferFactory().wrap(bits);
		response.setStatusCode(HttpStatus.UNAUTHORIZED);
		//指定编码，否则在浏览器中会中文乱码
		response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
		return response.writeWith(Mono.just(buffer));
	}
}
